<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\controller;

use think\facade\Log;
use think\facade\Request;
use think\facade\Session;

class FrontController extends BaseController
{
    public $noCheckLoginAction = []; // 标注不检测登录的 action
    public $noCheckLoginController = false; // 标注不检测登录的 Controller
    public $siteWholePlatform = false; // 是否开启移动端全端支持，开启后可以在《微信》《H5》使用
    private $openId = '';
    private $memberId = 0;

    public function initialize()
    {
        parent::initialize();
        $this->siteWholePlatform = $this->sysConfig['site_whole_platform'];
        $this->assign('siteWholePlatform', $this->siteWholePlatform);
        $request = Request::instance();
        $this->getMemberId();
        $this->getOpenId();

        if (env('WECHAT_DEBUG', 0)) {
            // TODO:测试参数
            $this->openId = 'ol6IA1vh9Tr-mmEda9hybGrJ3OjY';
            $this->memberId = 5;
        }

        $controllerName = $request->controller();
        $actionName = $request->action();

        $this->assign('controllerName',$controllerName);
        $this->assign('actionName',$actionName);

        // 是不检测的控制器 或者 标注不检测登录的 action ，直接返回
        if (true == $this->noCheckLoginController || in_array($actionName, $this->noCheckLoginAction)) {
            return;
        }
        // 有登录信息
        if(!empty($this->openId) && !empty($this->memberId)){
            return;
        }

        // 开启全端支持
        if ('true' == $this->siteWholePlatform) {
            $goBackUrl = base64_encode(request()->url());
            session('go_back_url',$goBackUrl);
            $this->error('获取登录信息失败，请刷新或者重新打开页面',url('Publics/login'));
            return;
        }
        elseif('false' == $this->siteWholePlatform){
            // 不开启全端支持，获取微信token
            $session_key = 'w_wechat_oauth_user';
            $session     = Session::get($session_key);
            $officialAccount = \Naixiaoxin\ThinkWechat\Facade::officialAccount();
            if (empty($session)) {
                if ($request->get('code')) {
                    // 取到 存 session
                    $session = $officialAccount->oauth->user();
                    Session::set($session_key, $session);
                    Log::info('微信OAuth2.0鉴权成功，' . json_encode($session, 256));
                    //跳转到登录
                    $this->redirect($this->getTargetUrl($request));
                }
                $url = $officialAccount->oauth->redirect($request->url(true))->getTargetUrl();
                $this->redirect($url);
            }
            else{
                $user = $officialAccount->user->get($session['original']['openid']);
                // session 存在 的时候进行赋值
                $this->setOpenId($session['original']['openid']);
                $weChatData = $session['original'];
                if($user['subscribe'] > 0){
                    $weChatData['is_follow'] = $user['subscribe'];
                    $weChatData['followtime'] = $user['subscribe_time'];
                }
                else{
                    $weChatData['is_follow'] = 0;
                    $weChatData['followtime'] = 0;
                }
                $this->setMemberId($this->getMemberIdByWechat($weChatData));
            }
        }
        else{
            $this->error('未知设置');
            return;
        }
    }

    protected function getTargetUrl($request)
    {
        $param = $request->get();
        if(isset($param['code'])){
            unset($param['code']);
        }
        if(isset($param['state'])){
            unset($param['state']);
        }
        return $request->baseUrl() . (empty($param) ? '' : ('?' . http_build_query($param)));
    }

    /**
     * 根据 微信 信息 获取会员ID
     * @param $sessionOriginal
     * @return int|mixed|string
     */
    private function getMemberIdByWechat($sessionOriginal){
        $memberLogic = new \app\common\logic\MemberLogic();
        return $memberLogic->_getMemberIdByWechat($sessionOriginal);
    }

    public function getOpenId(){
        if (empty($this->openId)) {
            $this->openId = Session::get('openid');
        }
        return $this->openId;
    }
    public function setOpenId($val){
        Session::set('openid', $val);
        $this->openId = $val;
    }
    public function getMemberId(){
        if (empty($this->memberId)) {
            $this->memberId = Session::get('memberid');
        }
        return $this->memberId;
    }
    public function setMemberId($val){
        Session::set('memberid', $val);
        $this->memberId = $val;
    }

    /**
     * 获取是否微信端 通过openid来判断 前缀是 wap_user_ 的是 H5 端，否则是微信端用户
     * @return bool true 是微信端
     */
    public function getIsWechat(){
        return !(!(strpos($this->getOpenId(), 'wap_user_') === FALSE));
    }

    public function logout(){
        $this->setOpenId('');
        $this->setMemberId(0);
        Session::flush();
        $this->success('退出成功');
    }
}